package com.example.yiwei.crm.view.activity.customerActivity;

import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.example.yiwei.crm.R;
import com.example.yiwei.crm.dao.customerDao;
import com.example.yiwei.crm.data.GetClue;
import com.example.yiwei.crm.data.GetContact;
import com.example.yiwei.crm.data.GetCustumer;
import com.example.yiwei.crm.data.GetUpdataCustomer;
import com.example.yiwei.crm.dao_impl.customerDaoImpl;
import com.example.yiwei.crm.entity.ClueMeesageEntity;
import com.example.yiwei.crm.entity.CustomerMessageEntity;
import com.example.yiwei.crm.view.Class.getSpinnerClass;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class CustomerAddBaseMessageActivity extends AppCompatActivity{
    List<Map<String, String>> list;
    public static CustomerAddBaseMessageActivity a;
    CustomerMessageEntity customer;
    List<String> client_list;
    // 省数据集合
    private ArrayList<String> mListProvince = new ArrayList<String>();
    // 市数据集合
    private ArrayList<ArrayList<String>> mListCiry = new ArrayList<ArrayList<String>>();
    // 区数据集合
    private ArrayList<ArrayList<ArrayList<String>>> mListArea = new ArrayList<ArrayList<ArrayList<String>>>();
    private OptionsPickerView<String> mOpv;
    private JSONObject mJsonObj;
    private String Filename;
    private TextView mtCity;
    String category;
    Button btn_show;
    ImageView img_next,img_back;
    Spinner client_category;
    EditText edit_name,edit_age,edit_ID_number,edit_address;
    LinearLayout linearLayout;
    String tx;
    private ArrayAdapter adapter;
    private int typeID;
    List<Map<String,String>> customerSpinner;
    private static int Tag;
    String result;
    private TextView titleText;
    RadioGroup rg_sex;
    int sex;
    RadioButton rb_men,rb_women;
    private  String UTag ;
    ClueMeesageEntity clue;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer_add_base_message);
        Intent intent = getIntent();
        UTag = intent.getStringExtra("Tag");
        a=this;
        Tag=0;
        mtCity = (TextView) findViewById(R.id.userBase_txt_show);

       if (UTag==null){
           GetCustumer.create();
           GetContact.create();
       }
        if ("update".equals(UTag)){
            customer=GetUpdataCustomer.get();
        }else{
            customer = GetCustumer.get();
        }
        initJsonData(this);
        // 初始化Json数据
        initJsonDatas();
        // 创建选项选择器对象
        mOpv = new OptionsPickerView<String>(this);

        // 设置标题
        mOpv.setTitle("选择城市");

        // 设置三级联动效果
        mOpv.setPicker(mListProvince, mListCiry, mListArea, true);

        // 设置是否循环滚动
        mOpv.setCyclic(false, false, false);

        // 设置默认选中的三级项目
        mOpv.setSelectOptions(0, 0, 0);

        // 监听确定选择按钮
        mOpv.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                // 返回的分别是三个级别的选中位置
                tx = mListProvince.get(options1) + mListCiry.get(options1).get(option2) + mListArea.get(options1).get(option2).get(options3);
                mtCity.setText(tx);
            }
        });
       btn_show= (Button) findViewById(R.id.userBase_layout_show);
        // 点击弹出选项选择器
        btn_show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mOpv.show();
            }
        });
        img_back= (ImageView) findViewById(R.id.user_add_img_back);
        img_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        client_category= (Spinner) findViewById(R.id.userBase_spinner_client_category);
        edit_address= (EditText) findViewById(R.id.userBase_edit_address);
        edit_age= (EditText) findViewById(R.id.userBase_edit_age);
        edit_name= (EditText) findViewById(R.id.userBase_edit_name);
        rg_sex= (RadioGroup) findViewById(R.id.customer_add_base_sex);
        rb_men= (RadioButton) findViewById(R.id.customer_add_base_men);
        rb_women= (RadioButton) findViewById(R.id.customer_add_base_women);
        edit_ID_number= (EditText) findViewById(R.id.userBase_edit_ID_number);
        rg_sex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (i==rb_men.getId()){
                    sex=1;
                }else{
                    sex=2;
                }
            }
        });
        if ("ClueToCustomer".equals(getIntent().getStringExtra("ClueToCustomerTag"))){
            showMessage();
        }
        if ("ClueToCustomerGroup".equals(getIntent().getStringExtra("ClueToCustomerGroupTag"))){
            showMessage();
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                final customerDao customer=new customerDaoImpl();
                result = getSpinnerClass.getSpinner();
                customerSpinner=customer.querySpinnerContent(result,1);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        client_list= new ArrayList<>();
                        client_list.add(0,"");
                        for (int i2=0;i2<customerSpinner.size();i2++){
                            client_list.add( customerSpinner.get(i2).get("KHLX02"));
                        }
                        adapter = new ArrayAdapter(CustomerAddBaseMessageActivity.this,android.R.layout.simple_spinner_item, client_list);
                        client_category.setAdapter(adapter);
                        client_category.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                category=client_category.getSelectedItem().toString();
                                for (int i = 0;i<customerSpinner.size();i++){
                                    if (category.equals(customerSpinner.get(i).get("KHLX02"))){
                                        typeID = Integer.valueOf(customerSpinner.get(i).get("KHLX01"));
                                    }
                                 }
                            }
                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {

                            }
                        });
                        if (UTag!=null){
                            if (UTag.equals("update")){
                                initData();
                            }
                        }
                    }
                });
            }
        }).start();
        img_next= (ImageView) findViewById(R.id.userBase_btn_next);
        img_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                  if (!"".equals(edit_name.getText().toString())&&!"".equals(edit_ID_number.getText().toString())){
                      customer.setClient_name(edit_name.getText().toString());
                      if(!edit_age.getText().toString().equals("")) {
                          customer.setClient_age(Integer.parseInt(edit_age.getText().toString()));
                      }
//                      if ((!edit_gender.getText().toString().equals(""))){
//                          if (edit_gender.getText().toString().equals("男")){
//                              customer.setClient_gender(1);
//                          }else if (edit_gender.getText().toString().equals("女")){
//                              customer.setClient_gender(2);
//                          }
//
//                      }
                      customer.setClient_gender(sex);
                      customer.setIDNumber(edit_ID_number.getText().toString());
                      if(tx!=null){
                          customer.setClient_Address(tx+edit_address.getText().toString());
                      }else{
                          customer.setClient_Address(edit_address.getText().toString());
                      }

                      customer.setClient_Category_id(typeID);
                      Intent intent=new Intent(CustomerAddBaseMessageActivity.this,CustomerAddContactMessageActivity.class);
                      intent.putExtra("spinner",result);
                      intent.putExtra("Tag",Tag);
                      if ("ClueToCustomer".equals(getIntent().getStringExtra("ClueToCustomerTag"))){
                          intent.putExtra("ClueToCustomerTag","ClueToCustomer");
                      }
                      if ("ClueToCustomerGroup".equals(getIntent().getStringExtra("ClueToCustomerGroupTag"))){
                          intent.putExtra("ClueToCustomerGroupTag","ClueToCustomerGroup");
                      }
                      intent.putExtra("UTag",UTag);
                      intent.putExtra("kehuchiTag",getIntent().getStringExtra("kehuchiTag"));
                      startActivity(intent);
                      Tag= 1;
                  }else{
                      Toast.makeText(CustomerAddBaseMessageActivity.this, "请填写必填项", Toast.LENGTH_SHORT).show();
                  }


            }
        });


    }
    //线索转化为客户，以前的信息显示方法
    public void showMessage(){
        clue=GetClue.get();
        edit_name.setText(clue.getClue_name());
        if(customer.getClient_gender()==1){
            rb_men.setChecked(true);
        }else if (customer.getClient_gender()==2){
            rb_women.setChecked(true);
        }
        edit_age.setText(clue.getClue_age()+"");

    }

    /** 从assert文件夹中读取省市区的json文件，然后转化为json对象 */
    private void initJsonData(Context context) {
        Filename = "city.json";
        try {
            StringBuffer sb = new StringBuffer();
            AssetManager am = context.getAssets();
            InputStream is = am.open(Filename);
            int len = -1;
            byte[] buf = new byte[1024];
            while ((len = is.read(buf)) != -1) {
                sb.append(new String(buf, 0, len, "GBK"));
            }
            is.close();
            mJsonObj = new JSONObject(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    /** 初始化Json数据，并释放Json对象 */
    private void initJsonDatas(){
        try {
            JSONArray jsonArray = mJsonObj.getJSONArray("citylist");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonP = jsonArray.getJSONObject(i);// 获取每个省的Json对象
                String province = jsonP.getString("name");
                ArrayList<String> options2Items_01 = new ArrayList<String>();
                ArrayList<ArrayList<String>> options3Items_01 = new ArrayList<ArrayList<String>>();
                JSONArray jsonCs = jsonP.getJSONArray("city");
                for (int j = 0; j < jsonCs.length(); j++) {
                    JSONObject jsonC = jsonCs.getJSONObject(j);// 获取每个市的Json对象
                    String city = jsonC.getString("name");
                    options2Items_01.add(city);// 添加市数据
                    ArrayList<String> options3Items_01_01 = new ArrayList<String>();
                    JSONArray jsonAs = jsonC.getJSONArray("area");
                    for (int k = 0; k < jsonAs.length(); k++) {
                        options3Items_01_01.add(jsonAs.getString(k));// 添加区数据
                    }
                    options3Items_01.add(options3Items_01_01);
                }
                mListProvince.add(province);// 添加省数据
                mListCiry.add(options2Items_01);
                mListArea.add(options3Items_01);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mJsonObj = null;
    }
    public void initData(){
        customer= GetUpdataCustomer.get();
        titleText = (TextView) findViewById(R.id.usermess_bar_title);
        titleText.setText("修改信息");
        edit_name.setText(customer.getClient_name());
        if(customer.getClient_gender()==1){
            rb_men.setChecked(true);
        }else if (customer.getClient_gender()==2){
            rb_women.setChecked(true);
        }
        edit_age.setText(customer.getClient_age()+"");
        edit_ID_number.setText(customer.getIDNumber());
        edit_address.setText(customer.getClient_Address());
        SpinnerAdapter spadapter = client_category.getAdapter();
        String khlx = "";
        for (int i = 0;i<customerSpinner.size();i++){
            if (customer.getClient_Category_id()==Integer.valueOf(customerSpinner.get(i).get("KHLX01"))){
               khlx= customerSpinner.get(i).get("KHLX02");

            }
        }
        SpinnerAdapter adapter1 = client_category.getAdapter();
        for (int i =0;i<adapter1.getCount();i++){
            if (khlx.equals(adapter1.getItem(i).toString())){
                client_category.setSelection(i);
            }
        }
    }
}
